# Python推导式（列表推导式、元组推导式、字典推导式和集合推导式）详解
## Python列表推导式
## [表达式 for 迭代变量 in 可迭代对象 [if 条件表达式]]
a_range = range(10)
# 对 a_range 执行 for 表达式
a_list = [x * x for x in a_range]
# a_list集合包含10个元素
print("a_list =", a_list)
print()

b_list = [x * x for x in a_range if x % 2 == 0]
# b_list包含5个元素
print("b_list =", b_list)
print()

d_list = [(x, y) for x in range(5) for y in range(4)]
# d_list列表包含20个元素
print("d_list =", d_list)
print()

e_list = [[x, y, z] for x in range(5) for y in range(4) for z in range(6)]
# e_list列表包含120个元素
print("e_list =", e_list)
print()

src_a = [30, 12, 66, 34, 39, 78, 36, 57, 121]
src_b = [3, 5, 7, 11]
# 只要y能整除x，就将它们配对在一起
result = [(x, y) for x in src_b for y in src_a if y % x == 0]
print("result =", result)
print()

## Python元组推导式
## (表达式 for 迭代变量 in 可迭代对象 [if 条件表达式])
a = (x for x in range(1, 10))
print("a =", a)
print(tuple(a))
print()

a = (x for x in range(1, 10))
for i in a:
    print(i, end = " ")
print(tuple(a))
print()

a = (x for x in range(1, 10))
print("a.__next__() =", a.__next__())
print("a.__next__() =", a.__next__())
print("a.__next__() =", a.__next__())
a = tuple(a)
print("转换后的元组：", a)
print()

## Python字典推导式
## {表达式 for 迭代变量 in 可迭代对象 [if 条件表达式]}
list_demo = ["C语言中文网", "c.bianchent.net"]
# 将列表中各字符串值为键，各字符串的长度为值，组成键值对
new_dict = {key:len(key) for key in list_demo}
print("new_dict =", new_dict)
print()

old_dict = {'C语言中文网': 6, 'c.bianchent.net': 15}
new_dict = {v: k for k, v in old_dict.items()}
print("new_dict =", new_dict)
print()

old_dict = {'C语言中文网': 6, 'c.bianchent.net': 15}
new_dict = {v: k for k, v in old_dict.items() if v > 10}
print("new_dict =", new_dict)
print()

## Python集合推导式
## {表达式 for 迭代变量 in 可迭代对象 [if 条件表达式]}
set_new = {i ** 2 for i in range(3)}
print("set_new =", set_new)
print()

tuple_demo = (1, 1, 2, 3, 4, 5, 6, 6)
set_new = {x ** 2 for x in tuple_demo if x % 2 == 0}
print("set_new =", set_new)
print()

dict_demo = {"1": 1, "2": 2, "3": 3}
set_new = {x for x in dict_demo.keys()}
print("set_new =", set_new)
print()
